package com.keter.framework.cloud.component.interceptor;

import com.google.common.base.Strings;
import com.keter.framework.web.component.sequence.SIDHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 所有服务接收HTTP请求时通用的MVC拦截器
 */
public class GlobalInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(GlobalInterceptor.class);

    @Autowired
    protected SIDHolder sidHolder;

    @Override  
    public boolean preHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler)  {
        // 防止因加载顺序导致SIDHolder未初始化异常
        if(sidHolder == null){
            BeanFactory factory =
                    WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            sidHolder = (SIDHolder) factory.getBean("SIDHolder");
        }
        receiveSid(request);
        return true;
    }

    /**
     * 接收请求中传递的SID
     * @param request
     */
    private void receiveSid(HttpServletRequest request) {
        if(!Strings.isNullOrEmpty(request.getHeader(SIDHolder.KEY_SID))){
            sidHolder.setSid(Long.valueOf(request.getHeader(SIDHolder.KEY_SID)));
        }
        else{
            sidHolder.generate();
        }
    }

    @Override  
    public void postHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler,  
            ModelAndView modelAndView) {
    }  

    @Override  
    public void afterCompletion(HttpServletRequest request,  
            HttpServletResponse response, Object handler, Exception ex) {
    }
}